package com.cf.base.sp.engine.impl;

import com.alibaba.fastjson.JSON;
import com.cf.base.sp.bean.ObjectType;
import com.cf.base.sp.bean.SerializerInfo;
import com.cf.base.sp.engine.Converter;
import com.cf.base.sp.engine.JsonEngine;
import com.cf.base.sp.type.MapType;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author yangji
 */
public class DefaultConverterImpl implements Converter {

    private JsonEngine json;

    public DefaultConverterImpl(JsonEngine iJson) {
        this.json = iJson;
    }

    @Override
    public <T> String toString(T t) {
        return json.toJsonString(t);
    }

    @Override
    public <T> T parseObject(SerializerInfo info, String content) {

        try {
            Class valueClass = Class.forName(info.valueClass);
            Type type = null;
            if (info.type == ObjectType.Map) {
                Class keyClass = Class.forName(info.keyClass);
                type = new MapType(Map.class, new Type[]{keyClass, valueClass});
            }
            if (info.type == ObjectType.List) {
                type = new MapType(List.class, new Type[]{valueClass});
            }
            if (info.type == ObjectType.Set) {
                type = new MapType(Set.class, new Type[]{valueClass});
            }
            if (info.type == ObjectType.Object) {
                type = valueClass;
            }
            return json.fromJson(content,type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
